/**
 * Author: Lily Jiang
 * Create Time: 2020/3/18
 * Description:
 */
import React from "react";

export default class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false,
            errorType: '',
            errorTemplate: {
                'ChunkLoadError': {
                    template: <div onClick={this.tryAgain}>页面加载失败，点击重试</div>,
                    callback: 'loadPageError'
                }
            }
        };
    }

    static getDerivedStateFromError(error) {
        // 更新 state 使下一次渲染能够显示降级后的 UI
        let obj = {
            hasError: true
        }

        if (error.toString().indexOf('ChunkLoadError') > -1) {
            obj.errorType = 'ChunkLoadError'
        }

        return obj;
    }

    tryAgain = () => {
        this.setState({
            hasError: false,
            errorType: ''
        })
    }

    componentDidCatch(error, errorInfo) {
        // this.props[this.state.errorTemplate[this.state.errorType].callback](error)
    }

    render() {
        return this.state.hasError && this.state.errorTemplate[this.state.errorType] && this.state.errorTemplate[this.state.errorType].template || this.props.children;
    }
}